﻿#include "emailwindow.h"
#include "ui_emailwindow.h"
#include<QMessageBox>
#include <QByteArray>
#include <QString>
#include<QListWidgetItem>
#include<QCheckBox>
#include<QLabel>
#include<QSqlQuery>
#include<QSqlQueryModel>
#include <QSqlDatabase>
#include<QRegularExpression>
#include<QRegularExpressionMatch>
#include<QThread>
QRegularExpression EmailWIndow::temp("(.*?)[(](.*?)[)]");
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
EmailWIndow::EmailWIndow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EmailInterface)
{
    this->setAttribute(Qt::WA_DeleteOnClose);
    ui->setupUi(this);
    //TODO title  SIZE
    db.setDatabaseName("C:\\LIBDB\\data.db");
    this->windowTitle().append("email");
    ui->titleLine->setPlaceholderText("标题：");
    ui->contentText->setPlaceholderText("请编辑您所要发送的内容:");
    ui->lineEdit->setClearButtonEnabled(true);
    listAll();

}
void EmailWIndow::listAll(){
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("D:\\Users\\lenovo\\Desktop\\combine\\library\\combine\\data.db");
    QSqlQuery query(db);
    if(!db.open()){
        qDebug()<<"fail to open ";
    }
    QString q=QString("SELECT * FROM Reader");
    query.exec(q);
    while(query.next()){
        QString ID = query.value("ID").toString();
        QString name = query.value("name").toString();
        QString email = query.value("email").toString();
        QListWidgetItem *item = new QListWidgetItem();
        QCheckBox *checkBox= new QCheckBox();
        ui->listWidget->addItem(item);//在ListWidget中添加一个条目
        ui->listWidget->setItemWidget(item, checkBox);//在这个条目中放置CheckBox
        checkBox->setText(QString("%1(%2)").arg(name,email));
        //
        qDebug()<<"ID :"<<ID <<"\tname:"<<name<<"\temail: "<<email;
    }
    db.close();
}

EmailWIndow::~EmailWIndow()
{
    delete ui;
}

void EmailWIndow::on_esc_clicked()
{
    this->close();
}


void EmailWIndow::on_send_clicked()
{
    QStringList storage;
    if(QMessageBox::Yes ==QMessageBox::question(this,"再次确认","是否确认发送？")){
        //找选中
        for(int i = 0;i<ui->listWidget->count();i++){
            QListWidgetItem *item = ui->listWidget->item(i);
            QCheckBox *checkBox = static_cast<QCheckBox*>(ui->listWidget->itemWidget(item));
            if(checkBox->isChecked()){
                //选中 进行操作
                storage.append(checkBox->text());
                //
                qDebug()<<checkBox->text()<<Qt::endl;
            }
        }
        if(storage.empty()){
            QMessageBox::warning(this,"警告","您尚未选中发送对象，请重新选中！");
        }else{
            QString title;
            QString content;
            content = ui->contentText->toPlainText();
            title = ui->titleLine->text();
            int size = storage.size();
            for (int i = 0;i<size ;i++){
                QString address = EmailWIndow::temp.match(storage[i]).captured(2);
                QString user = EmailWIndow::temp.match(storage[i]).captured(1);
                //TODO 定制内容
                Email email(address);
                email.SendEmail(title,content);
                QThread::sleep(1);
            }
            QMessageBox::information(this,"发送成功！","邮件已成功发送！");
            ui->contentText->clear();
            ui->titleLine->clear();
            on_not_all_clicked();
        }
    }
}


void EmailWIndow::on_select_all_clicked()
{
    for(int i = 0;i<ui->listWidget->count();i++){
        QListWidgetItem *item = ui->listWidget->item(i);
        QCheckBox *checkBox = static_cast<QCheckBox*>(ui->listWidget->itemWidget(item));
        checkBox->setCheckState(Qt::Checked);
    }
}


void EmailWIndow::on_not_all_clicked()
{
    for(int i = 0;i<ui->listWidget->count();i++){
        QListWidgetItem *item = ui->listWidget->item(i);
        QCheckBox *checkBox = static_cast<QCheckBox*>(ui->listWidget->itemWidget(item));
        checkBox->setCheckState(Qt::Unchecked);
    }

}


void EmailWIndow::on_pushButton_clicked()
{
    //TODO 选择  用数据库
    //TODO 选择后退出的状态保持
    QString obj = ui->lineEdit->text();
    if(obj==""){
        ui->listWidget->clear();
        listAll();
    }else{
        ui->listWidget->clear();
//        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//        db.setDatabaseName("D:\\Users\\lenovo\\Desktop\\combine\\library\\combine\\data.db");
        QSqlQuery query(db);
        if(!db.open()){
            qDebug()<<"fail to open ";
        }
        //TODO search mode ID
        QString command = "SELECT * FROM Reader where name like '%"+obj+"%'"+"or email like '%"+obj+"%'";
        QString q=QString(command);
        query.exec(q);
        while(query.next()){
            QString ID = query.value("ID").toString();
            QString name = query.value("name").toString();
            QString email = query.value("email").toString();
            QListWidgetItem *item = new QListWidgetItem();
            QCheckBox *checkBox= new QCheckBox();
            ui->listWidget->addItem(item);//在ListWidget中添加一个条目
            ui->listWidget->setItemWidget(item, checkBox);//在这个条目中放置CheckBox
            checkBox->setText(QString("%1(%2)").arg(name,email));
            //
            qDebug()<<"ID :"<<ID <<"\tname:"<<name<<"\temail: "<<email;
        }
        db.close();
    }
}


void EmailWIndow::on_note_clicked()
{
    QStringList storage;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:\\LIBDB\\data.db");
    QSqlQuery query(db);
    QDateTime cur = QDateTime::currentDateTime();
    if(!db.open()){
        qDebug()<<"fail to open ";
    }else{
        QString q=QString("SELECT * FROM book_info where borrow = 'borrowed'");
        query.exec(q);
        while(query.next()){
            QString ID = query.value("borrower_ID").toString();
            qDebug()<<"ID :"<<ID;
            QString tempname=ID;
            if(!storage.contains(ID)){
                QDateTime date = query.value("borrowed_date").toDateTime();
                int gap = cur.daysTo(date);
                if(gap<=0){
                    qDebug()<<ID;
                    storage.append(ID);
                    QSqlQuery find(db);
                    QString cmd = "SELECT * FROM Reader where ID = '"+ID+"'";

                    QSqlQuery bksql(global::bok->book_db);
                    QString book_new =QString("update Reader set book_overtime= '%1' "
                                              "where ID='%3'")
                            .arg("1")
                            .arg(ID)
                            .arg(ID);
                    global::overtime="1";
                    qDebug()<<book_new;
                    bksql.exec(book_new);


                    find.exec(cmd);
                    while(find.next()){
                        QString name = find.value("name").toString();
                        QString email = find.value("email").toString();
                        Email tmp(email);
                        QString title = "mlibrary还书提醒";
                        QString content ="尊敬的"+name+":\n"+"    您好！\n"+"    本条邮件为还书提醒，您在本馆所借的书籍及还书日期如下：\n";
                        QSqlQuery search_book(db);
                        QString cmd = "SELECT * FROM book_info where borrower_ID = '"+ID+"'";
                        search_book.exec(cmd);
                        while(search_book.next()){
                            QString book = search_book.value("book").toString();
                            QString ddl = search_book.value("borrowed_date").toString();
                            content += "        书籍：《"+book+"》"+"\t应还日期："+ddl+"\n";
                        }
                        content+="    感谢您在本馆借阅，祝您生活愉快！";
                        qDebug()<<content<<Qt::endl;
                        tmp.SendEmail(title,content);
                        QThread::sleep(1);
                    }
                }
            }
        }
        if(storage.empty()){
            QMessageBox::information(this,"提示","暂无逾期人员！");
        }else{
            QMessageBox::information(this,"提示","已提醒应还人员！");
        }
        db.close();
    }
}

